import axios from "axios";
import {Loading} from "element-ui";

let loading

function loadingShow() {
  loading = Loading.service({
    lock: true,
    // spinner: "el-icon-loading",
    background: "rgba(255, 255, 255, .8)",
    text: "加载中"
  });
}

function loadingHide() {
  loading.close();
}

// create an axios instance
const service = axios.create({
  baseURL: "/api", // api 的 base_url
  // baseURL: "http://api.zyark2.com:3000/mock/1441/api", // api 的 base_url
  timeout: 5000 // request timeout
});

service.interceptors.request.use(
  config => {
    loadingShow();
    // Do something before request is sent
    if (localStorage.getItem('token')) {
      config.headers.token = localStorage.getItem('token');
      // config.headers["X-Requested-With"] = "XMLHttpRequest";
    }
    config.headers["Content-Type"] = "application/json;charset=UTF-8";

    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  response => {
    loadingHide();
    return response;
  },
  error => {
    if (error && error.config) {
      loadingHide();
    }
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

export default service;
